package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.News;
import cn.wolfcode.trip.base.domain.NewsContent;
import cn.wolfcode.trip.base.mapper.NewsContentMapper;
import cn.wolfcode.trip.base.mapper.NewsMapper;
import cn.wolfcode.trip.base.query.NewsQuery;
import cn.wolfcode.trip.base.service.INewsService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 日报业务接口实现类
 */
@Service
public class NewsServiceImpl implements INewsService {

    @Autowired
    private NewsMapper newsMapper;

    @Autowired
    private NewsContentMapper contentMapper;

    /**
     * 分页方法
     * @param qo
     * @return
     */
    public PageInfo query(NewsQuery qo) {
        //开始分页
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<News> list = newsMapper.selectForList(qo);
        return new PageInfo(list);
    }

    /**
     * 新增或修改方法
     * @param news
     */
    public void saveOrUpdate(News news) {
        //设置为草稿状态
        if(news.getState()==null){
            news.setState(News.STATE_AUDIT);
        }

        //设置浏览量为0
        if(news.getBrowseNum()==null){
            news.setBrowseNum(0);
        }

        if(news.getId()!=null){
            //更新日报基本信息
            newsMapper.updateByPrimaryKey(news);
            //获得日报内容
            NewsContent newsContent = news.getNewsContent();
            //主键关联
            newsContent.setId(news.getId());
            //更新日报内容
            contentMapper.updateByPrimaryKey(newsContent);
        }else{
            //保存日报基本信息
            newsMapper.insert(news);
            //获得日报内容
            NewsContent newsContent = news.getNewsContent();
            //主键关联
            newsContent.setId(news.getId());
            //保存日报内容
            contentMapper.insert(newsContent);
        }
    }

    /**
     * 根据id查询日报内容
     * @param id
     * @return
     */
    public NewsContent getContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    /**
     * 修改日报状态
     * @param news
     * @return
     */
    public void updateState(News news) {
        //如果是发布状态就需要设置发布时间
        if(news.getState()==News.STATE_RELEASE||news.getState()==News.STATE_REJECT){
            news.setReleaseTime(new Date());
        }
        newsMapper.updateState(news);
    }

    /**
     * 根据日报id获取日报对象
     * @param id
     * @return
     */
    public News getById(Long id) {
        return newsMapper.selectByPrimaryKey(id);
    }
}
